//
//  SJ_AudioPlayer.m
//  音频
//
//  Created by 孙嘉胤 on 16/7/16.
//  Copyright © 2016年 Sun. All rights reserved.
//

#import "SJ_AudioPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import "UIImageView+WebCache.h"

#define  WIDTH [UIScreen mainScreen].bounds.size.width
#define  HEIGHT [UIScreen mainScreen].bounds.size.height
@interface SJ_AudioPlayer ()
@property (nonatomic, strong) NSArray *arrOfPlayList;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, assign) BOOL isPlaying;
//@property (nonatomic, assign) int currentPlayIndex;
@property (nonatomic, strong) id playbackTimeObserver;
@property (nonatomic, retain) UISlider *sliderProgress;
@property (nonatomic, retain) UIButton *playButton;
@property (nonatomic, retain) UIProgressView *prgBufferProgress;
@property (nonatomic, retain) UIImageView *imageView;
@property (nonatomic, retain) CABasicAnimation *rotationAnimation;
@end

@implementation SJ_AudioPlayer


- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    self.rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    self.rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    self.rotationAnimation.duration =10;
    self.rotationAnimation.cumulative = YES;
    self.rotationAnimation.repeatCount = NSIntegerMax;
    
    [self.imageView.layer addAnimation:self.rotationAnimation forKey:@"rotationAnimation"];

    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    
    [self.player removeTimeObserver:self.playbackTimeObserver];
    [self.player removeObserver:self forKeyPath:@"status"];
    

    self.player = nil;
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    self.playButton = nil;
    self.sliderProgress = nil;
    self.prgBufferProgress = nil;
    self.imageView = nil;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil arrayOfUrl:(NSMutableArray *)arrayOfUrl {
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        self.arrOfPlayList = arrayOfUrl;


    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.isPlaying = NO;
    self.playButton.enabled = NO;
    self.sliderProgress.value = 0;
    UIImageView *bgImgView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    bgImgView.image = [UIImage imageNamed:@"背景"];
    bgImgView.contentMode = UIViewContentModeScaleAspectFill;
    //[bgImgView setImageToBlur: [UIImage imageNamed:@"huoying4.jpg"] blurRadius:20 completionBlock:nil];
    bgImgView.userInteractionEnabled = YES;
    [self.view addSubview:bgImgView];
    
    /*
     9      毛玻璃的样式(枚举)
     10      UIBlurEffectStyleExtraLight,
     11      UIBlurEffectStyleLight,
     12      UIBlurEffectStyleDark
     13      */
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    effectView.frame = CGRectMake(0, 0, bgImgView.frame.size.width, bgImgView.frame.size.height);
    [bgImgView addSubview:effectView];
    [self createView];
    self.player = [[AVPlayer alloc]initWithPlayerItem:[[AVPlayerItem alloc]initWithURL:self.arrOfPlayList[self.currentPlayIndex]]];
    self.player.volume = 1.0;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PlayDidEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    [self.player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    __weak SJ_AudioPlayer *weakVC = self;
    __weak AVPlayer *weakPlayer = self.player;
    self.playbackTimeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float currentTime = weakPlayer.currentTime.value / weakPlayer.currentItem.currentTime.timescale;
        weakVC.sliderProgress.value = currentTime;
        //更新缓冲进度
        NSTimeInterval timeInterval = [weakVC availableDuration];
        //计算缓冲进度
        NSLog(@"TIme Interval:%f",timeInterval);
        CMTime duration = weakPlayer.currentItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        [weakVC.prgBufferProgress setProgress:timeInterval / totalDuration  animated:YES];
        
    }];
    
}

- (void)createView {
    self.playButton = [[UIButton alloc]init];
    self.playButton.frame = CGRectMake(180, 170, 50, 50);
    self.prgBufferProgress = [[UIProgressView alloc]initWithFrame:CGRectMake(30, HEIGHT - 50, WIDTH - 60, 2)];
    self.sliderProgress = [[UISlider alloc]initWithFrame:CGRectMake(30, HEIGHT - 100, WIDTH - 60, 2)];
    [self.playButton setImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
    UIButton *forWard = [UIButton buttonWithType:UIButtonTypeCustom];
    UIButton *next = [UIButton buttonWithType:UIButtonTypeCustom];
    [next setImage:[UIImage imageNamed:@"下一曲"] forState:UIControlStateNormal];
    next.frame = CGRectMake(310, 170, 50, 50);
    [next addTarget:self action:@selector(doNext:) forControlEvents:UIControlEventTouchUpInside];
    [forWard setImage:[UIImage imageNamed:@"上一曲"] forState:UIControlStateNormal];
    forWard.frame = CGRectMake(50, 170, 50, 50);
    [forWard addTarget:self action:@selector(doForward:) forControlEvents:UIControlEventTouchUpInside];
    self.imageView = [[UIImageView alloc]init];
    [self.imageView sd_setImageWithURL:self.arrOfImage[self.currentPlayIndex]];
    self.imageView.frame = CGRectMake(0, 0, 200, 200);
    self.imageView.center = self.view.center;
    self.imageView.layer.masksToBounds = YES;
    self.imageView.layer.cornerRadius = 100;
    
    [self.view addSubview:self.playButton];
    [self.view addSubview:self.prgBufferProgress];
    [self.view addSubview:self.sliderProgress];
    [self.view addSubview:forWard];
    [self.view addSubview:next];
    [self.view addSubview:self.imageView];
    
    
    [self.playButton addTarget:self action:@selector(handlePlayButton:) forControlEvents:UIControlEventTouchUpInside];
 
    [self.sliderProgress addTarget:self action:@selector(doChangeProgress:) forControlEvents:UIControlEventValueChanged];
}


- (void)PlayDidEnd{
    
    NSLog(@"播放完毕");
    //在这里处理完毕后的事情
    
}

//观察着方法,用来监听播放器状态
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    //当播放器状态(status)改变时,回进入次判断
    if ([keyPath isEqualToString:@"status"]) {
        if (self.player.status == AVPlayerStatusReadyToPlay) {
            //等到播放器状态为就绪时,让播放按钮可用
            [self.playButton setEnabled:YES];
        }
    }
    
}

- (void)handlePlayButton:(UIButton *)button{
    
    if (self.isPlaying) {
        [self.player pause];
        self.isPlaying = NO;
        [self.playButton setImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
        
    }else{
        self.isPlaying = YES;
        [self.player play];
        [self.playButton setImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateNormal];
        //获取当前播放音视频的总时长(s秒)
        self.sliderProgress.maximumValue = self.player.currentItem.duration.value / self.player.currentItem.duration.timescale;
        
        
    }
    
}

- (void)doChangeProgress:(UISlider *)slider {
    
    //初始化指定时间去播放
    [self.player seekToTime:CMTimeMake(self.sliderProgress.value, 1)];
    
}

- (void)doForward:(UIButton *)button {
    
    if (self.currentPlayIndex - 1 >= 0) {
        //初始化一个播放对象
        AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:self.arrOfPlayList[self.currentPlayIndex - 1]];
        //将初始化好的对象替换掉当前播放对象
        [self.player replaceCurrentItemWithPlayerItem:item];
        [self.imageView sd_setImageWithURL:self.arrOfImage[self.currentPlayIndex - 1]];
        if (self.isPlaying) {
            
            [self.player play];
        }
        
        self.currentPlayIndex--;
    }
    
}

- (void)doNext:(UIButton *)button {
    
    //如果当前播放+1后,小于播放列表的count,表明可以播放下一曲
    if (self.currentPlayIndex + 1 < self.arrOfPlayList.count) {
        //初始化一个播放对象
        [self.imageView sd_setImageWithURL:self.arrOfImage[self.currentPlayIndex + 1]];
        AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:self.arrOfPlayList[self.currentPlayIndex + 1]];
        //将初始化好的对象替换掉当前对象
        [self.player replaceCurrentItemWithPlayerItem:item];
        if (self.isPlaying) {
            
            [self.player play];
        }
        self.currentPlayIndex++;
    }
    
}



- (NSTimeInterval)availableDuration {
    
    NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
    //获取缓冲区域
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    //计算缓冲总进度
    NSTimeInterval result = startSeconds + durationSeconds;
    return result;
    
}

@end
